
from flask import request
from plugins_v3._login.login import login
from utils.decorators.check_sign import check_sign
from utils.decorators.request_limit import request_limit
from utils.session import session
from . import api, config
from utils.decorators.cache import cache
from lxml import etree


@api.route('/studies', methods=['GET'])
@check_sign({'name', 'passwd'})
@request_limit()
@cache({'name'}, 180)
def handle_studies():
    name = request.args.get('name', type=str)
    passwd = request.args.get('passwd', type=str)
    cookies = login(name, passwd)
    post_data = {
        '_search': 'false',
    }
    studies_list = []
    studies = session.post(config.studies_url, post_data, cookies=cookies).json()
    all_studies = get_all_studies(cookies)
    studies = studies['items']
    for study in studies:
        one_list = {
            'name': study['kcxzmc'],
            'gpa': study.get('gpa', ''),
            'xf': study['hdxf']
        }
        studies_list.append(one_list)
    studies_list.append({'name': '所有课程平均GPA', 'gpa': all_studies})
    return {
        'code': 0,
        'data': studies_list
    }


def get_all_studies(cookies):
    rq = session.get(url=config.all_studies_url, cookies=cookies).content.decode()
    tree = etree.HTML(rq)
    all_studies = tree.xpath('normalize-space(//*[@id="alertBox"]/font[2]/font/text())')
    return all_studies
